import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    children: [
      {
        path: 'resources',
        name: 'Resources',
        component: () => import('../views/Resources.vue')
      },
      {
        path: 'my-resources',
        name: 'MyResources',
        component: () => import('../views/MyResources.vue')
      },
      {
        path: 'resource/:id',
        name: 'ResourceDetail',
        component: () => import('../views/ResourceDetail.vue')
      },
      {
        path: 'publish',
        name: 'Publish',
        component: () => import('../views/Publish.vue')
      },
      {
        path: 'my-borrows',
        name: 'MyBorrows',
        component: () => import('../views/MyBorrows.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.path !== '/login' && to.path !== '/register' && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router 